import { Controller, Get, Post, Body, Query, Param, Delete, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ResourceService } from './resource.service';
import { Resource } from './entities/resource.entity';
import { diskStorage } from 'multer';
import { extname } from 'path';
import * as sharp from 'sharp';
// import { Jimp } from "jimp";

@Controller('resources')
export class ResourceController {
    constructor(private readonly resourceService: ResourceService) { }

    @Get(':md5')
    async findByMd5(@Param('md5') md5: string): Promise<Resource> {
        return this.resourceService.findByMd5(md5);
    }

    @Post('upload')
    @UseInterceptors(
        FileInterceptor('file', {
            storage: diskStorage({
                destination: process.env.FILE_PATH || './uploads',
                filename: (req, file, callback) => {
                    const timestamp = Date.now();
                    const ext = extname(file.originalname) || '.jpg';
                    callback(null, `${timestamp}${ext}`);
                },
            }),
            limits: {
                fileSize: 20 * 1024 * 1024, // 限制为20MB
            },
        }),
    )
    async uploadFile(@UploadedFile() file: Express.Multer.File, @Body('md5') md5: string): Promise<Resource> {
        const newResource = new Resource();
        newResource.name = file.filename;
        newResource.path = `${process.env.ASSETS_URL}/${file.filename}`;
        newResource.md5 = md5;

        // 检查是否为图片文件
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
        const ext = extname(file.originalname).toLowerCase() || ".jpg";

        if (imageExtensions.includes(ext)) {
            const timestamp = file.filename.split('.')[0];
            const thumbnailName = `${timestamp}.min${ext}`;
            console.log("thumbnailName", thumbnailName);
            const thumbnailPath = `${process.env.FILE_PATH}/${thumbnailName}`;

            try {
                // 生成缩略图
                await sharp(file.path)
                    .resize(300, 300, {
                        fit: 'inside',      // 保持宽高比
                        withoutEnlargement: true  // 不放大小图片
                    })
                    .toFile(thumbnailPath);

                // 添加缩略图路径到资源记录
                newResource.thumbnail = `${process.env.ASSETS_URL}/${thumbnailName}`;
            }
            catch (error) {
                console.error('Error generating thumbnail:', error);
                newResource.thumbnail = ""
            }
            
        }
        else {
            newResource.thumbnail = ''
        }

        return this.resourceService.saveResource(newResource);
    }

    @Delete(':md5')
    async deleteResource(@Param('md5') md5: string): Promise<void> {
        await this.resourceService.deleteByMd5(md5);
    }

    @Get()
    async findResources(@Query('page') page: number = 1, @Query('limit') limit: number = 10): Promise<{ resources: Resource[]; total: number }> {
        const [resources, total] = await this.resourceService.findWithPagination(page, limit);
        return { resources, total };
    }
}